package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SaveSysActivityDetail;
import com.ruoyi.system.domain.SocietyManage;
import com.ruoyi.system.domain.SysFinanceLog;
import com.ruoyi.system.mapper.SocietyManageMapper;
import com.ruoyi.system.mapper.SysActivityDetailMapper;
import com.ruoyi.system.mapper.SysFinanceLogMapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysActivityDetail;
import com.ruoyi.system.service.ISysActivityDetailService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 活动详情Controller
 *
 * @author ruoyi
 * @date 2022-01-29
 */
@RestController
@RequestMapping("/system/detail")
public class SysActivityDetailController extends BaseController {

  @Autowired
  private ISysActivityDetailService sysActivityDetailService;

  @Autowired
  private SysActivityDetailMapper sysActivityDetailMapper;

  @Autowired
  private SocietyManageMapper societyManageMapper;

  @Autowired
  private SysFinanceLogMapper sysFinanceLogMapper;

  /**
   * 查询活动详情列表
   */
  @GetMapping("/list")
  public TableDataInfo list(SysActivityDetail sysActivityDetail) {
    startPage();
    List<SysActivityDetail> list = sysActivityDetailService
        .selectSysActivityDetailList(sysActivityDetail);
    return getDataTable(list);
  }


  /**
   * 查询活动详情列表
   */
  @PostMapping("/rejectSociety")
  public AjaxResult rejectSociety(@RequestBody SysActivityDetail sysActivityDetail) {
    SysActivityDetail sysActivityDetail1 = sysActivityDetailMapper
        .selectSysActivityDetailByActivityId(sysActivityDetail.getActivityId());

    sysActivityDetail1.setUpdateBy(SecurityUtils.getUsername());
    sysActivityDetail1.setUpdateTime(new Date());
    sysActivityDetail1.setApprovalUserId(SecurityUtils.getUserId());
    sysActivityDetail1.setApprovalUserName(SecurityUtils.getUsername());
    sysActivityDetail1.setApprovalStatus("2");
    sysActivityDetail1.setRejectReason(sysActivityDetail.getRejectReason());
    sysActivityDetailMapper.updateSysActivityDetail(sysActivityDetail1);

    return AjaxResult.success("拒绝成功");
  }

  /**
   * 查询活动详情列表
   */
  @PutMapping("/applySocirfy/{activityId}")
  public AjaxResult applySocirfy(@PathVariable("activityId") Long activityId) {
    SysActivityDetail sysActivityDetail1 = sysActivityDetailMapper
        .selectSysActivityDetailByActivityId(activityId);

    sysActivityDetail1.setUpdateBy(SecurityUtils.getUsername());
    sysActivityDetail1.setUpdateTime(new Date());
    sysActivityDetail1.setApprovalUserId(SecurityUtils.getUserId());
    sysActivityDetail1.setApprovalUserName(SecurityUtils.getUsername());
    sysActivityDetail1.setApprovalStatus("1");
    sysActivityDetailMapper.updateSysActivityDetail(sysActivityDetail1);

    return AjaxResult.success("审批成功");
  }


  /**
   * 导出活动详情列表
   */
  @Log(title = "活动详情", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  public void export(HttpServletResponse response, SysActivityDetail sysActivityDetail) {
    List<SysActivityDetail> list = sysActivityDetailService
        .selectSysActivityDetailList(sysActivityDetail);
    ExcelUtil<SysActivityDetail> util = new ExcelUtil<SysActivityDetail>(SysActivityDetail.class);
    util.exportExcel(response, list, "活动详情数据");
  }

  /**
   * 获取活动详情详细信息
   */
  @GetMapping(value = "/{activityId}")
  public AjaxResult getInfo(@PathVariable("activityId") Long activityId) {
    return AjaxResult
        .success(sysActivityDetailService.selectSysActivityDetailByActivityId(activityId));
  }

  /**
   * 新增活动详情
   */
  @Log(title = "活动详情", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody @Valid SaveSysActivityDetail sysActivityDetail) {
    return toAjax(sysActivityDetailService.insertSysActivityDetail(sysActivityDetail));
  }

  /**
   * 修改活动详情
   */
   /* @PreAuthorize("@ss.hasPermi('system:detail:edit')")
    @Log(title = "活动详情", businessType = BusinessType.UPDATE)
    @PutMapping*/
  public AjaxResult edit(@RequestBody SysActivityDetail sysActivityDetail) {
    return toAjax(sysActivityDetailService.updateSysActivityDetail(sysActivityDetail));
  }

  /**
   * 删除活动详情
   */
  @Log(title = "活动详情", businessType = BusinessType.DELETE)
  @DeleteMapping("/{activityIds}")
  public AjaxResult remove(@PathVariable Long[] activityIds) {
    return toAjax(sysActivityDetailService.deleteSysActivityDetailByActivityIds(activityIds));
  }


  @Log(title = "活动审核", businessType = BusinessType.UPDATE)
  @PostMapping("/auditActivityMethod/{activityId}")
  @Transactional(rollbackFor = Exception.class)
  public AjaxResult auditActivityMethod(@PathVariable("activityId") Long activityId,
      String rejectReason, String approvalStatus) {
    if ("2".equals(approvalStatus) && !StringUtils.isNotBlank(rejectReason)) {
      throw new ServiceException("请填写拒绝原因");
    }
    SysActivityDetail sysActivity = sysActivityDetailMapper
        .selectSysActivityDetailByActivityId(activityId);
    SocietyManage societyManage = societyManageMapper
        .selectSocietyManageById(sysActivity.getSocietyId());

    if (sysActivity.getActivityId() == null) {
      throw new ServiceException("此活动不存在");
    }

    SysActivityDetail sysActivityDetail = new SysActivityDetail();
    sysActivityDetail.setActivityId(activityId);
    sysActivityDetail.setApprovalStatus(approvalStatus);
    sysActivityDetail.setApprovalUserId(SecurityUtils.getUserId());
    sysActivityDetail.setApprovalUserName(SecurityUtils.getUsername());
    sysActivityDetail.setApprovalTime(DateUtils.getNowDate());
    sysActivityDetail.setApprovalTime(DateUtils.getNowDate());
    sysActivityDetail.setRejectReason(rejectReason);
    sysActivityDetailMapper.updateSysActivityDetail(sysActivityDetail);

    // 活动需要经费
    Double activityFund = sysActivity.getActivityFund();
    double amount = societyManage.getExpenditure() - activityFund;
    if (amount < 0) {
      throw new ServiceException("社团活动经费不支持");
    }

    // 审核 -> 减少金额 -> 记录日志
    if ("1".equals(approvalStatus)) {
      societyManage.setExpenditure(amount);
      societyManageMapper.updateSocietyManage(societyManage);

      if (activityFund > 0D) {
        // 记录日志
        SysFinanceLog sysFinanceLog = new SysFinanceLog();
        sysFinanceLog.setSocietyId(sysActivity.getSocietyId() + "");
        sysFinanceLog.setSocietyName(sysActivity.getSocietyName());
        sysFinanceLog.setOperator(sysActivity.getApplyUserName());
        sysFinanceLog.setFinanceDetail("-" + activityFund);
        sysFinanceLog.setRemark(sysActivity.getActivityName() + "活动经费");
        sysFinanceLogMapper.insertSysFinanceLog(sysFinanceLog);
      }
    }

    return AjaxResult.success("审核成功");
  }

  @PostMapping("/queryUnAuditList")
  @Transactional(rollbackFor = Exception.class)
  @ApiOperation("查询审核活动列表")
  public TableDataInfo queryUnAuditList() {
    startPage();
    SysActivityDetail sysActivityDetail = new SysActivityDetail();
    if (!SecurityUtils.isAdmin(SecurityUtils.getUserId())) {
      if (SecurityUtils.isTeacher()) {
        sysActivityDetail.setApprovalUserId(SecurityUtils.getUserId());
      }
    }
    return getDataTable(sysActivityDetailMapper.selectSysActivityDetailList(sysActivityDetail));
  }
}
